#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/10/19 15:11
# file: user.py
# author: lotus163

from fastapi import APIRouter, Depends

from backend.core.deps import UserDepends, get_user_depends
from backend.core.result import ResultData, result_success, Result
from backend.core.security import get_token

router = APIRouter(prefix="/cache", tags=["redis缓存"], dependencies=[Depends(get_token)])


@router.get("", response_model=ResultData, summary='获取redis信息')
async def get_redis_info(user_depends: UserDepends = Depends(get_user_depends)):
    redis = user_depends.redis
    info_dict = await redis.info()
    cmdstat_dict = await redis.info(section="commandstats")
    cmdstat_list = redis.get_cmdstat_list(cmdstat_dict)
    dbsize = await redis.dbsize()
    return result_success(data={"commandStats": cmdstat_list, "info": info_dict, "dbSize": dbsize})


@router.delete("/clearCacheAll", response_model=Result, summary='删除所有redis缓存')
async def clear_redis_cache_all(user_depends: UserDepends = Depends(get_user_depends)):
    await user_depends.redis.flushdb()
    return result_success()


@router.delete("/clearCacheKey/{cacheKey}", response_model=Result, summary='根据key删除redis缓存')
async def clear_redis_cache_by_key(cacheKey: str, user_depends: UserDepends = Depends(get_user_depends)):
    await user_depends.redis.delete(cacheKey)
    return result_success()


@router.delete("/clearCacheName/{cacheName}", response_model=Result, summary='根据name删除redis缓存')
async def clear_redis_cache_by_name(cacheName: str, user_depends: UserDepends = Depends(get_user_depends)):
    redis = user_depends.redis
    keys = await redis.keys(cacheName + "*")
    for key in keys:
        await redis.delete(key)
    return result_success()


@router.get("/getKeys/{cacheName}", response_model=ResultData, summary='根据key获取redis缓存key')
async def get_redis_cache_by_name(cacheName: str, user_depends: UserDepends = Depends(get_user_depends)):
    keys = await user_depends.redis.keys(cacheName + "*")
    return result_success(data=keys)


@router.get("/getNames", response_model=ResultData, summary='获取redis缓存Names')
async def get_cache_names(user_depends: UserDepends = Depends(get_user_depends)):
    return result_success(data=user_depends.redis.get_cache_name_infos())


@router.get("/getValue/{cacheName}/{cacheKey}", response_model=Result, summary='根据key获取redis缓存value')
async def get_cache_value(cacheName: str, cacheKey: str, user_depends: UserDepends = Depends(get_user_depends)):
    cache_key = cacheKey.split(":")[-1]
    cache_value = await user_depends.redis.get(cacheKey)
    return result_success(data={"cacheName": cacheName, "cacheKey": cache_key, "cacheValue": cache_value, "remark": ""})
